const express = require("express");
const router = express.Router();
const file = require("./封装");
const mylog = function (req, res, next) {
  if (req.body.name != "") {
    next();
  } else {
    res.json("没有访问到权限");
  }
};
// 读取
router.get("/Read", async (req, res) => {
  let carData = await file.getFileData("./data621.json");
  res.json({
    code: 200,
    message: "success",
    data: carData.car || [],
  });
});
// 添加
router.post("/Create", mylog, async (req, res) => {
  try {
    // 获取数据
    let data = await file.getFileData("./data621.json");
    let counter = parseInt(await file.getFileData("./1.text")) || 0;

    // 确保car数组
    if (!data.car) {
      data.car = [];
    }
    const createTime = new Date().toLocaleString();
    let newItem = {
      ...req.body,
      创建时间: createTime,
      修改时间: createTime,
      id: `${counter + 1}`,
    };
    //数据列表
    data.car.push(newItem);
    await file.setFileData("./1.text", (counter + 1).toString());
    const isSaved = await file.setFileData("./data621.json", data);
    if (isSaved) {
      res.json({
        code: 200,
        message: "Car created successfully.",
        data: newItem,
      });
    } else {
      throw new Error("失败");
    }
  } catch (error) {
    console.error("Error during creation:", error);
    res.status(500).json({ code: 500, message: "Internal server error." });
  }
});
//删除
router.delete("/Delete", async (req, res) => {
  var data = await file.getFileData("./data621.json");
  //打印获取到的数据
  let data2 = req.body.id;
  console.log(data2);
  data.car = data.car.filter((item) => item.id != data2);
  var result = await file.setFileData("./data621.json", data);
  if (!result) {
    res.json({
      code: 500,
      message: "fail",
    });
  }
  res.json({
    code: 200,
    message: "success",
    data: data.car,
  });
});
// 修改
router.put("/Update", async (req, res) => {
  try {
    // 确保请求中包含ID
    if (!req.body.id) {
      return res.status(400).json({ code: 400, message: "请求中缺少“id" });
    }
    // 获取当前数据
    const data = await file.getFileData("./data621.json");
    // 查找要更新的项的索引
    const index = data.car.findIndex((car) => car.id === req.body.id);
    if (index === -1) {
      // 如果找不到对应ID的项
      return res.status(404).json({ code: 404, message: "Car not found." });
    }
    const updateData = {
      ...(req.body.name !== undefined && { name: req.body.name }),
      ...(req.body.price !== undefined && { price: req.body.price }),
      ...(req.body.color !== undefined && { color: req.body.color }),
      修改时间: req.body.修改时间 || new Date().toLocaleString(),
    };
    // 更新
    data.car[index] = { ...data.car[index], ...updateData };
    // 保存更新后的数据到文件
    const isSaved = await file.setFileData("./data621.json", data);
    if (isSaved) {
      // 返回成功响应，可以按需决定是否返回更新后的单项还是整个列表
      res.json({
        code: 200,
        message: "Car updated successfully.",
        data: data.car[index],
      });
    } else {
      res
        .status(500)
        .json({ code: 500, message: "Failed to save the updated data." });
    }
  } catch (error) {
    console.error("更新时出错:", error);
    res.status(500).json({ code: 500, message: "Internal server error." });
  }
});
//搜索数据
router.get("/soso", async (req, res) => {
  var data = await file.getFileData("./data621.json");
  var data2 = req.query.id;
  car = data.car.filter((item) => item.id == data2);
  res.json({
    code: 200,
    message: "success",
    data: car,
  });
});
router.get("/soso1", mylog, async (req, res) => {
  var data = await file.getFileData("./data621.json");
  var data2 = req.query.name;
  car = data.car.filter((item) => item.name === data2);
  if (car.length == 0) {
    res.json({
      code: 500,
      message: "错误",
    });
    return;
  }
  res.json({
    code: 200,
    message: "success",
    data: car,
  });
});
module.exports = router;
